<?php
include_once 'config.php';

class UploadFile
{
    protected $saveFileDir = 'UploadDir';
    protected $allowExts=['image/gif','image/jpeg','image/pjpeg'];
    protected $maxSize=2*1024*1024;//<2M

    public function __construct(array $params)
    {
        if($params['saveFileDir']){
            $this->saveFileDir = $params['saveFileDir'];
        }
    }

    function uploadFiles()
    {
        $result = [];
        $result['msg'] = '文件上传失败';
        $result['status'] = false;
        $result['pics'] = [];
        $savePath = $_SERVER['DOCUMENT_ROOT'] ."/". $this->saveFileDir . "/" .date('Ymd') . "/";
        $savePathUrl = APP_DOMAIN ."/". $this->saveFileDir . "/" .date('Ymd') . "/";
        $this->ensure_writable_dir($savePath);

        try {
            if (empty($_FILES)) {
                throw new Exception('ERROR:未接收到文件数据');
            }

            $filesCount = count($_FILES['files']['name']);

            for ($i = 0; $i < $filesCount; $i++) {
                //判断文件类型
                if(!in_array($_FILES['files']['type'][$i],$this->allowExts)){
                    throw new Exception('ERROR:文件类型不允许:' . $_FILES['files']['name'][$i]);
                }
                //判断文件大小是否超出
                if($_FILES['files']['size'][$i]>$this->maxSize){
                    throw new Exception('ERROR:文件太大:' . $_FILES['files']['name'][$i].$_FILES['files']['size'][$i]);
                }

                $newFileName=time().'_'.rand(2000,3000);
                $newImgDir = $savePath . $newFileName;
                $res = move_uploaded_file($_FILES['files']['tmp_name'][$i], $newImgDir);
                if ($res === false) {
                    throw new Exception('ERROR:图片上传失败:' . $_FILES['files']['name'][$i]);
                }
                $result['pics'][] = $savePathUrl.$newFileName;
            }

            $result['status'] = true;
            $result['msg'] = '成功上传' . $filesCount . '个文件';

        } catch (Exception $e) {
            $result['msg'] = $e->getMessage();
        }

        return $result;
    }


    function ensure_writable_dir($dir)
    {
        if (!file_exists($dir)) {
            mkdir($dir, 0766, true);
            chmod($dir, 0766);
            chmod($dir, 0777);
        } else if (!is_writable($dir)) {
            chmod($dir, 0766);
            chmod($dir, 0777);
            if (!is_writable($dir)) {
                throw new FileSystemException("目录 $dir 不可写");
            }
        }
    }
}
